package cn.bdqn.sp.service.impl;

import cn.bdqn.sp.mapper.SysUserMapper;
import cn.bdqn.sp.pojo.SysUser;
import cn.bdqn.sp.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public SysUser login(String account, String password) throws RuntimeException{
        // 1.先按用户名查询
        SysUser sysUser = sysUserMapper.selectUser(account);

        // 2.判断,如果没有查询结果，说明用户名不存在
        if (sysUser == null){
            throw new RuntimeException("用户不存在！");
        }

        // 3.判断密码是否正确
        if (!sysUser.getPassword().equals(password)){
            throw new RuntimeException("密码输入错误！");
        }

        // 4.都正确，返回查询的结果即可

        return sysUser;
    }

    @Override
    public List<SysUser> getUsers(SysUser sysUser) {
        return sysUserMapper.selectUsers(sysUser);
    }

    @Override
    public int addUser(SysUser sysUser) {
        return sysUserMapper.insertSelective(sysUser);
    }

    @Override
    public SysUser getUserById(Long id) {
        return sysUserMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateUser(SysUser sysUser) {
        return sysUserMapper.updateByPrimaryKeySelective(sysUser);
    }

    @Override
    public int deleteUser(Long id) {
        return sysUserMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int updatePassword(String account,String oldPassword, String newPassword) {
        // 1.验证旧密码对不对
        SysUser sysUser = sysUserMapper.selectUserByPwd(account, oldPassword);

        // 如果查不出数据的话，密码不对
        if (sysUser == null){
            throw new RuntimeException("旧密码输入不正确！");
        }

        // 2.修改密码，将旧密码改成新密码
        sysUser.setPassword(newPassword);
        int rs = sysUserMapper.updateByPrimaryKeySelective(sysUser);

        return rs;
    }

    @Override
    public SysUser getUserByAccount(String account) {
        return sysUserMapper.selectUser(account);
    }
}
